package com.game.caro.util;
/**
 * @author ngocbd@bitjsc.com
 * */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.game.caro.server.Config;

/**
 * lop nay de lay ra mot ket noi toi csdl
 * @author ngocbd@bitjsc.com
 *
 */
public class DatabaseUtils {

	private static Logger logger = LoggerFactory.getLogger(DatabaseUtils.class);
	private static GenericObjectPool pool =null;
	public static Connection getConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException
	{
		if(pool==null)
		{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			// create a generic pool
		     pool = new GenericObjectPool(null);
	
		    // use the connection factory which will wraped by
		    // the PoolableConnectionFactory
		    DriverManagerConnectionFactory cf =  new DriverManagerConnectionFactory(
		                                            Config.CONNECT_URI, 
		                                            Config.CONNECT_USERNAME,
		                                            Config.CONNECT_PASSWORD);
	
		    PoolableConnectionFactory pcf =  new PoolableConnectionFactory(cf, pool, null, "SELECT 1", false, true);
	
		    // register our pool and give it a name
		    new PoolingDriver().registerPool("bitPool", pool);
		    logger.debug("init datatabase connection pool [bitPool]...");
		}
	    // get a connection and test it
	        Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:bitPool");

	        // now we can use this pool the way we want.
	        logger.debug("Are we connected? " + !conn.isClosed());
	        logger.debug("Idle Connections: " + pool.getNumIdle() + ", out of " + pool.getNumActive());
		return conn;
	}
}
